<?php

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Controller;
use think\Request;
use think\Db;
use think\db\Query;
use app\admin\model\TeacherModel;
use app\admin\model\SubjectModel;

class SubjectController extends AdminBaseController
{
    public function index()
    {
        $name=$this->request->param('name');
        $subject =Db::name('subject')
            ->join('cmf_teacher','cmf_teacher.id=cmf_subject.teacher_id')
            ->field('cmf_teacher.name as teacher_name,cmf_subject.*')
            ->where(function (Query $query) use ($name){
                if ($name){
                    $query->where('cmf_subject.name','like',"%$name%");
                }
            })
            ->order('id DESC')
            ->paginate(3,false,['query'=>$this->request->param()]);
        $page=$subject->render();
        return view('',['subject'=>$subject,'page'=>$page]);
    }
    public function add()
    {
        $teacher=TeacherModel::select();
        return $this->fetch('',['teacher'=>$teacher]);
    }
    public function addPost()
    {
        $data=input();
        if (empty($data['name'])){
            $this->error('班级名不能为空');
        }
        $add=SubjectModel::create($data);
        if ($add){
            $this->success('添加成功','subject/index');
        }else{
            $this->error('添加失败');
        }
    }

    public function edit()
    {
        $data=input();
        $subject=SubjectModel::get($data['id']);
        $teacher=TeacherModel::select();
        return view('',['subject'=>$subject,'teacher'=>$teacher]);
    }

    public function editPost()
    {
        $data=input();
        $edit=SubjectModel::update($data,['id'=>$data['id']]);
        /*$hasSubject=Db::name('subject')->where(['name'=>input('name')])->find();
        if ($hasSubject){
            $this->error('科目已经存在');
        }*/
        if ($edit){
            $this->success('修改成功','subject/index');
        }else{
            $this->error('修改失败');
        }
    }
    public function delete($id)
    {
        $del=SubjectModel::destroy($id);
        if ($del){
            $this->success('删除成功！','subject/index');
        }else{
            $this->error('删除失败');
        }
    }
    public function delAll(){
        $ids=input('ids/a');
        $del=Db::name('subject')->delete($ids);
        if ($del){
            return ['code'=>200,'msg'=>'删除成功'];
        }else{
            return ['code'=>100,'msg'=>'删除失败'];
        }
    }
}
